'use client';

import { useState } from 'react';

interface JobDistributionFormData {
  jobId: string;
  jobName: string;
  matchCriteria: {
    tags: string[];
    category: string;
    skillLevel: string;
  };
  totalAgents: number;
  assignedCount: number;
  responseCount: number;
  assignedAgentId: string;
  assignedAgentName: string;
}

interface JobDistributionAgent {
  id: string;
  agentId: string;
  agentName: string;
  workStatus: 'ASSIGNED' | 'WORKING' | 'COMPLETED' | 'FAILED' | 'CANCELLED' | 'TIMEOUT';
  executionResult: string;
  startedAt: string;
  completedAt: string;
  progress: number;
  errorMessage: string;
  executionTimeMs: number;
  retryCount: number;
}

export default function JobDistributionForm() {
  const [formData, setFormData] = useState<JobDistributionFormData>({
    jobId: '',
    jobName: '',
    matchCriteria: {
      tags: [],
      category: '',
      skillLevel: '',
    },
    totalAgents: 0,
    assignedCount: 0,
    responseCount: 0,
    assignedAgentId: '',
    assignedAgentName: '',
  });

  const [assignedAgents, setAssignedAgents] = useState<JobDistributionAgent[]>([
    {
      id: '1',
      agentId: 'agent1',
      agentName: 'AI开发Agent',
      workStatus: 'WORKING',
      executionResult: '',
      startedAt: '2024-01-15T10:00:00',
      completedAt: '',
      progress: 65,
      errorMessage: '',
      executionTimeMs: 45000,
      retryCount: 0,
    },
    {
      id: '2',
      agentId: 'agent2',
      agentName: '数据分析Agent',
      workStatus: 'COMPLETED',
      executionResult: '任务已完成，分析报告已生成',
      startedAt: '2024-01-15T09:30:00',
      completedAt: '2024-01-15T11:30:00',
      progress: 100,
      errorMessage: '',
      executionTimeMs: 120000,
      retryCount: 0,
    },
  ]);

  const [tagInput, setTagInput] = useState('');

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    if (name.startsWith('matchCriteria.')) {
      const field = name.split('.')[1];
      setFormData(prev => ({
        ...prev,
        matchCriteria: {
          ...prev.matchCriteria,
          [field]: value,
        },
      }));
    } else {
      setFormData(prev => ({ ...prev, [name]: value }));
    }
  };

  const handleAddTag = () => {
    if (tagInput.trim() && !formData.matchCriteria.tags.includes(tagInput.trim())) {
      setFormData(prev => ({
        ...prev,
        matchCriteria: {
          ...prev.matchCriteria,
          tags: [...prev.matchCriteria.tags, tagInput.trim()],
        },
      }));
      setTagInput('');
    }
  };

  const handleRemoveTag = (tagToRemove: string) => {
    setFormData(prev => ({
      ...prev,
      matchCriteria: {
        ...prev.matchCriteria,
        tags: prev.matchCriteria.tags.filter(tag => tag !== tagToRemove),
      },
    }));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    console.log('Job Distribution Form Data:', formData);
    // 这里可以添加API调用逻辑
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'ASSIGNED':
        return 'bg-blue-100 text-blue-800';
      case 'WORKING':
        return 'bg-yellow-100 text-yellow-800';
      case 'COMPLETED':
        return 'bg-green-100 text-green-800';
      case 'FAILED':
        return 'bg-red-100 text-red-800';
      case 'CANCELLED':
        return 'bg-gray-100 text-gray-800';
      case 'TIMEOUT':
        return 'bg-orange-100 text-orange-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'ASSIGNED':
        return '已分配';
      case 'WORKING':
        return '工作中';
      case 'COMPLETED':
        return '已完成';
      case 'FAILED':
        return '失败';
      case 'CANCELLED':
        return '已取消';
      case 'TIMEOUT':
        return '超时';
      default:
        return status;
    }
  };

  return (
    <div className="max-w-6xl mx-auto">
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-8">
        <h2 className="text-2xl font-bold text-gray-900 mb-6">任务分发管理</h2>
        
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 基本信息 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                任务ID *
              </label>
              <input
                type="text"
                name="jobId"
                value={formData.jobId}
                onChange={handleInputChange}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                任务名称 *
              </label>
              <input
                type="text"
                name="jobName"
                value={formData.jobName}
                onChange={handleInputChange}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                required
              />
            </div>
          </div>

          {/* 匹配标准 */}
          <div className="border-t pt-6">
            <h3 className="text-lg font-medium text-gray-900 mb-4">匹配标准</h3>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  分类
                </label>
                <input
                  type="text"
                  name="matchCriteria.category"
                  value={formData.matchCriteria.category}
                  onChange={handleInputChange}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  技能等级
                </label>
                <select
                  name="matchCriteria.skillLevel"
                  value={formData.matchCriteria.skillLevel}
                  onChange={handleInputChange}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">选择技能等级</option>
                  <option value="beginner">初级</option>
                  <option value="intermediate">中级</option>
                  <option value="advanced">高级</option>
                  <option value="expert">专家</option>
                </select>
              </div>
            </div>

            {/* 标签匹配 */}
            <div className="mt-4">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                匹配标签
              </label>
              <div className="flex gap-2 mb-2">
                <input
                  type="text"
                  value={tagInput}
                  onChange={(e) => setTagInput(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddTag())}
                  className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="输入标签后按回车或点击添加"
                />
                <button
                  type="button"
                  onClick={handleAddTag}
                  className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                >
                  添加
                </button>
              </div>
              <div className="flex flex-wrap gap-2">
                {formData.matchCriteria.tags.map((tag, index) => (
                  <span
                    key={index}
                    className="inline-flex items-center px-3 py-1 rounded-full text-sm bg-blue-100 text-blue-800"
                  >
                    {tag}
                    <button
                      type="button"
                      onClick={() => handleRemoveTag(tag)}
                      className="ml-2 text-blue-600 hover:text-blue-800"
                    >
                      ×
                    </button>
                  </span>
                ))}
              </div>
            </div>
          </div>

          {/* 分配统计 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                总Agent数量
              </label>
              <input
                type="number"
                name="totalAgents"
                value={formData.totalAgents}
                onChange={handleInputChange}
                min="0"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                已分配数量
              </label>
              <input
                type="number"
                name="assignedCount"
                value={formData.assignedCount}
                onChange={handleInputChange}
                min="0"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                响应数量
              </label>
              <input
                type="number"
                name="responseCount"
                value={formData.responseCount}
                onChange={handleInputChange}
                min="0"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
          </div>

          {/* 最终选中Agent */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                最终选中Agent ID
              </label>
              <input
                type="text"
                name="assignedAgentId"
                value={formData.assignedAgentId}
                onChange={handleInputChange}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                最终选中Agent名称
              </label>
              <input
                type="text"
                name="assignedAgentName"
                value={formData.assignedAgentName}
                onChange={handleInputChange}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
          </div>

          {/* 提交按钮 */}
          <div className="flex justify-end space-x-4">
            <button
              type="button"
              className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
            >
              取消
            </button>
            <button
              type="submit"
              className="px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
            >
              保存分发记录
            </button>
          </div>
        </form>

        {/* Agent分配列表 */}
        <div className="mt-8 border-t pt-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">Agent分配详情</h3>
          <div className="space-y-4">
            {assignedAgents.map((agent) => (
              <div
                key={agent.id}
                className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50 transition-colors"
              >
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-3">
                    <h4 className="font-medium text-gray-900">{agent.agentName}</h4>
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(agent.workStatus)}`}>
                      {getStatusText(agent.workStatus)}
                    </span>
                  </div>
                  <div className="text-sm text-gray-500">
                    Agent ID: {agent.agentId}
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                  <div>
                    <span className="text-gray-600">进度:</span>
                    <div className="mt-1">
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div
                          className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                          style={{ width: `${agent.progress}%` }}
                        ></div>
                      </div>
                      <span className="text-xs text-gray-500">{agent.progress}%</span>
                    </div>
                  </div>

                  <div>
                    <span className="text-gray-600">执行时间:</span>
                    <span className="ml-2 text-gray-900">{agent.executionTimeMs}ms</span>
                  </div>

                  <div>
                    <span className="text-gray-600">重试次数:</span>
                    <span className="ml-2 text-gray-900">{agent.retryCount}</span>
                  </div>
                </div>

                {agent.executionResult && (
                  <div className="mt-3 p-3 bg-gray-50 rounded text-sm">
                    <span className="text-gray-600">执行结果:</span>
                    <p className="mt-1 text-gray-900">{agent.executionResult}</p>
                  </div>
                )}

                {agent.errorMessage && (
                  <div className="mt-3 p-3 bg-red-50 rounded text-sm">
                    <span className="text-red-600">错误信息:</span>
                    <p className="mt-1 text-red-800">{agent.errorMessage}</p>
                  </div>
                )}

                <div className="mt-3 text-xs text-gray-500">
                  开始时间: {new Date(agent.startedAt).toLocaleString()}
                  {agent.completedAt && (
                    <span className="ml-4">
                      完成时间: {new Date(agent.completedAt).toLocaleString()}
                    </span>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
} 